package fortunetelling.fortunetelling;

import com.google.common.collect.Lists;
import fortunetelling.fortunetelling.bean.Fortune;
import fortunetelling.fortunetelling.listener.FishingEventListener;
import fortunetelling.fortunetelling.listener.PlayerInteractEventListener;
import fortunetelling.fortunetelling.utils.FortuneConvertUtils;
import fortunetelling.fortunetelling.utils.StringUtils;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.java.JavaPlugin;

import java.lang.reflect.Field;
import java.util.*;

public final class FortuneTelling extends JavaPlugin {

    public static Map<String, Fortune> FORTUNE_TELLING_MAP = new HashMap<>(1 << 4);
    public static long FORTUNE_TIME = 86400000;
//    public static long FORTUNE_TIME = 300000;

    /**
     * 抽签
     *
     * @param sender
     * @param commandLabel
     * @param args
     * @return
     */
    private static void fortuneTelling(CommandSender sender, String commandLabel, String[] args) {
        Fortune fortune = FORTUNE_TELLING_MAP.get(sender.getName());
        if (fortune != null) {
            sender.sendMessage("§4 您今日已经抽过签了！");
            sender.sendMessage("§a 你上次抽到的是 " + fortune.getName() + " ！");
            sender.sendMessage(fortune.getHint());
            sender.sendMessage(fortune.getPoem());
            return;
        }
        int randomInt = new Random().nextInt(5);
        List<String> list = Arrays.asList("大吉", "大凶", "凶", "半吉", "吉");
        String result = list.get(randomInt);
        sender.sendMessage("§a 你抽到的是 " + result + " ！");
        fortune = Optional.ofNullable(FortuneConvertUtils.translate(result)).orElse(new Fortune());
        sender.sendMessage(fortune.getHint());
        sender.sendMessage(fortune.getPoem());
        FORTUNE_TELLING_MAP.putIfAbsent(sender.getName(), fortune);
        // 进行概率调整

        // 开始计时，一天后移除
        new Timer().schedule(new TimerTask() {
            public void run() {
                sender.sendMessage("你现在又可以抽签了");
                FORTUNE_TELLING_MAP.remove(sender.getName());
            }
        }, FORTUNE_TIME);
    }

    /**
     * 查看对应吉凶信息
     *
     * @param sender
     * @param args
     * @return
     */
    private static void showFortuneTellingInfo(CommandSender sender, String[] args) {
        if (args.length != 2 || StringUtils.isEmpty(args[1])) {
            sender.sendMessage("请输入正确的命令");
            return;
        }
        sender.sendMessage("您输入的是" + args[1]);
        Fortune fortune = FortuneConvertUtils.translate(args[1]);
        if (fortune == null) {
            sender.sendMessage("请输入 大吉 大凶 凶 半吉 吉 任意一个");
            return;
        }
        sender.sendMessage(fortune.getHint());
        sender.sendMessage(fortune.getPoem());
    }

    @Override
    public void onEnable() {
        // 注册监听器
        getServer().getPluginManager().registerEvents(new FishingEventListener(), this);
        getServer().getPluginManager().registerEvents(new PlayerInteractEventListener(), this);
        // Plugin startup logic
        Field commandMapField = null;
        try {
            commandMapField = getServer().getClass().getDeclaredField("commandMap");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        assert commandMapField != null;
        commandMapField.setAccessible(true);
        CommandMap commandMap = null;
        try {
            commandMap = (CommandMap) commandMapField.get(getServer());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        assert commandMap != null;
        commandMap.register("zhanbu", new Command("zhanbu") {
            @Override
            public boolean execute(CommandSender sender, String commandLabel, String[] args) {
                if (!(sender instanceof Player)) {
                    sender.sendMessage("你不是人");
                    return false;
                }
                if (args.length == 0) {
                    FortuneTelling.fortuneTelling(sender, commandLabel, args);
                    return false;
                }
                if (("?".equalsIgnoreCase(args[0])) || ("？".equalsIgnoreCase(args[0]))) {
                    sender.sendMessage("输入/zhanbu ? 查看帮助");
                    sender.sendMessage("输入/zhanbu 进行占卜");
                    sender.sendMessage("输入/zhanbu i [吉凶] 查看对应吉凶信息");
                    sender.sendMessage("输入/zhanbu set [物品名] 获得该类型的转运符,不输入物品名则为手上物品");
                } else if ("i".equalsIgnoreCase(args[0])) {
                    FortuneTelling.showFortuneTellingInfo(sender, args);
                } else if ("set".equalsIgnoreCase(args[0])) {
                    Player player = (Player) sender;
                    if (!player.hasPermission(Permission.DEFAULT_PERMISSION.name())) {
                        sender.sendMessage("§4 你没有权限做这个");
                        return false;
                    }
                    if (args.length > 2) {
                        sender.sendMessage("§4 请输入正确的命令");
                        return false;
                    } else if (args.length == 1) {
                        PlayerInventory inventory = player.getInventory();
                        ItemStack item = inventory.getItemInMainHand();
                        ItemMeta itemMeta = item.getItemMeta();
                        if (itemMeta == null) {
                            sender.sendMessage("§4 你手上没有拿物品");
                            return false;
                        }
                        itemMeta.setDisplayName("转运符");
                        List<String> loreList = Optional.ofNullable(itemMeta.getLore()).orElse(new ArrayList<>());
                        loreList.add("转运符");
                        itemMeta.setLore(loreList);
                        item.setItemMeta(itemMeta);
                        sender.sendMessage("§a 已获得转运符");
                        return false;
                    }
                    if (StringUtils.isEmpty(args[1])) {
                        sender.sendMessage("§4 请输入正确的命令");
                        return false;
                    }
                    Material material = Material.matchMaterial(args[1]);
                    if (material == null) {
                        sender.sendMessage("§4 请输入正确的物品");
                        return false;
                    }
                    ItemStack item = new ItemStack(material);
                    ItemMeta itemMeta = item.getItemMeta();
                    if (itemMeta == null) {
                        sender.sendMessage("§4 未找到该物品的itemMeta");
                        return false;
                    }
                    itemMeta.setDisplayName("转运符");
                    List<String> loreList = Optional.ofNullable(itemMeta.getLore()).orElse(Lists.newArrayList());
                    loreList.add("转运符");
                    itemMeta.setLore(loreList);
                    item.setItemMeta(itemMeta);
                    sender.sendMessage("§a 已获得转运符");
                    player.getInventory().addItem(item);
                }
                return false;
            }
        });
        getLogger().info("占卜插件加载成功！");
    }

    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }

}
